#!/bin/bash
# Start ComfyUI script scheduler (Linux/Mac version)

# 获取脚本自身的绝对路径
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

PYTHON_VENV="$SCRIPT_DIR/../python/bin/python"
PY_SCRIPTS_DIR="$SCRIPT_DIR/py_scripts"
LAUNCHER="$PY_SCRIPTS_DIR/script_launcher.py"

echo "🚀 启动 ComfyUI 脚本调度器..."
echo

# 检查虚拟环境
if [ ! -x "$PYTHON_VENV" ]; then
  echo "[INFO] 未检测到虚拟环境，正在创建..."
  PYTHON_BIN=$(command -v python3 || command -v python)
  if [ -z "$PYTHON_BIN" ]; then
    echo "❌ Python解释器未找到，请先安装Python！"
    exit 1
  fi
  $PYTHON_BIN -m venv "$SCRIPT_DIR/../python"
  if [ ! -x "$PYTHON_VENV" ]; then
    echo "❌ 虚拟环境创建失败！"
    exit 1
  fi
  echo "[INFO] 虚拟环境创建成功: $PYTHON_VENV"
else
  echo "[INFO] 检测到虚拟环境: $PYTHON_VENV"
fi

# 激活虚拟环境并安装基础依赖包
echo "[INFO] 激活虚拟环境并检查依赖包..."
source "$SCRIPT_DIR/../python/bin/activate"

# 安装基础依赖包
echo "[INFO] 安装基础依赖包..."
"$PYTHON_VENV" -m pip install --upgrade pip
"$PYTHON_VENV" -m pip install requests huggingface_hub packaging setuptools psutil

echo "当前目录: $(pwd)"
echo "检查 py_scripts 目录:"
ls -la "$PY_SCRIPTS_DIR"

echo "检查 script_launcher.py:"
ls -la "$LAUNCHER"

echo "即将运行: $PYTHON_VENV $LAUNCHER"
"$PYTHON_VENV" "$LAUNCHER"

echo
echo "程序已退出..."
